/**
 *
 */
package com.yangtao.prototype.common.select.service.impl;

import com.yangtao.framework.cache.CacheFlyweight;
import com.yangtao.framework.cache.CacheManager;
import com.yangtao.framework.common.Option;
import com.yangtao.framework.service.BaseService;
import com.yangtao.framework.util.ReflectionUtils;
import com.yangtao.prototype.common.select.service.DataStoreType;
import com.yangtao.prototype.common.select.service.SelectService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class SelectServiceImpl extends BaseService implements SelectService {

	protected int maxSize = 5;

	@Override
	public List<Option> getSlaveList(String masterId, String type) {
//		return treeDao.getSubTrees(masterId, type);
		return null;
	}

	/**
	 * 根据所需要的数据类型和条件，加载不同的数据
	 *
	 * @param type         所需要的数据类型
	 * @param restrictions 约束条件
	 * @return
	 */
	@Override
	public List<Object> getStoreByType(DataStoreType type, Map<String, Object> restrictions) {
		Assert.notNull(type, "数据类型不能为空!");
		List retValue = null;
		switch (type) {
			case material:
				// retValue = materialDao.findStore(restrictions);
				break;
			case customer:
				break;
			case section:
				break;
			default:
				break;
		}
		return retValue;
	}

	/**
	 * 根据用户ID查找用户授权的主数据
	 *
	 * @param userId        用户Id
	 * @param dataStoreType 主数据类型
	 * @param keyWorld      过滤关键字
	 * @return
	 */
	@Override
	public List<Object> getStoreByUser(String userId, DataStoreType dataStoreType, String keyWorld, String matchString) {
		CacheManager cache = CacheFlyweight.getCache();
		Map<String, List<Object>> userCache = (Map<String, List<Object>>) cache.get(userId);
		if (userCache == null) {
			//计算缓存
		}
		List<Object> masterData = userCache.get(dataStoreType.toString());
		List<Object> ret = new ArrayList<Object>();
		if (masterData != null && masterData.size() > 0) {
			for (Object object : masterData) {
				if (ret.size() > maxSize) {
					return ret;
				}
				Object value = ReflectionUtils.getFieldValue(object, keyWorld);
				if (value != null) {
					if (filter(value.toString(), matchString)) {
						ret.add(object);
					}
				}
			}
		}
		return ret;
	}

	/**
	 * 判断两个字符串是否匹配
	 *
	 * @param value
	 * @param matcher
	 * @return
	 */
	public boolean filter(String value, String matcher) {
		int pos = matcher.indexOf("*");
		if (pos != -1) {
			matcher = matcher.substring(0, pos);
		}
		return value.indexOf(matcher) != -1;
	}

}
